/**
 * ValidateSaxParse
 * ------------------------
 * 
 * - This class will validate an XML document.
 * - Contains a list of observers (arraylist of constraints).
 * - The class is the subject in the Observer design pattern.
 * - Runs through the whole XML document by API SAXParser.
 * 
 * @author Caio Thomas
 * @version 1-10-2013 
 */
package model.validator;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;

import org.apache.xerces.parsers.SAXParser;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ValidateSaxParse extends DefaultHandler implements Serializable  {
	
	private static final long serialVersionUID = 1L;
	private ArrayList<ObserverSaxParser> constraints = new ArrayList<ObserverSaxParser>();
	private String chVal;	

	/* Functions of SaxParser */
	
	public void startDocument() {
    	for(ObserverSaxParser restricao:constraints){
    		restricao.startDocument();
        }				
	}

	public void endDocument() {
    	for(ObserverSaxParser restricao:constraints){
    		restricao.endDocument();
        }    		
	}
		
    public void startElement(String uri, String localName,String qName,  Attributes attributes) throws SAXException {
    	//for all constraint insert's
    	for(ObserverSaxParser restricao:constraints){
    		restricao.startElement(localName, qName, attributes);
        }    	
    }

    public void endElement(String uri, String localName, String qName) throws SAXException {    	    
    	//for all constraint insert's
    	for(ObserverSaxParser restricao:constraints){    	
    		restricao.endElement(localName, qName, chVal); 
    	}    	    	
    	
    	chVal = "";
    }

	public void characters(char ch[], int start, int length) {
		chVal = new String(ch, start, length).trim();		
	}	
                
    public void parse(String filename) {
    	if(constraints.size() == 0) //checks if size of constraints is zero
    		return;//don't have anything to validation    
				    	
    	try { 
	    	SAXParser sp = new SAXParser();
	        	    	
			for(ObserverSaxParser restricao:constraints) //creates structure to validation    	
				restricao.constructorValidate(); 
	    			    	
	    	sp.setContentHandler(this);
	        
	    	sp.parse(new InputSource(filename));             
		} catch (SAXException e) {
			System.out.println("Error: Sax Parse File.");
			e.printStackTrace();
		} catch(IOException e){
			System.out.println("Error: I/O File.");
	        e.printStackTrace();
	    } 
    } 
    
    public void add(ObserverSaxParser o){
    	constraints.add(o);
    }
    
    public void remove(ObserverSaxParser o){
    	constraints.remove(o);
    }	    
    
    public ArrayList<ObserverSaxParser> getConstraints(){
    	return constraints;
    }
    
    public void addAll(ArrayList<ObserverSaxParser> list){
    	constraints.addAll(list);
    }
}